package com.example.custsecurity.security.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//已认证的访问未授权的资源路径就会调用此方法
//注：容错处理方法
@Slf4j
@Component
public class CustAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {

        JSONObject result=new JSONObject();
        result.put("code",HttpServletResponse.SC_UNAUTHORIZED);
        result.put("message",e.getLocalizedMessage());

        PrintWriter pw = response.getWriter();
        pw.print(result);
        pw.flush();
        pw.close();
    }
}
